# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28 15:04:37 2017

@author: qiang.qian
"""
import json
import requests
import datetime
import sys

def getmail(uid):
    try:
        values = {
        	"BU":"BASE",
        	"Key":"email",
        	"Parameters":[]
        }
       
        values['UID'] = uid
        
        url = 'http://ws.members.ctripcorp.com/userprofileservice/api/GetUserProfileByKey'
        data = json.dumps(values)
        headers = {'content-type': 'application/json'}
        res = requests.post(url=url,data=data,headers=headers)
        
        j = json.loads(res.text)
        
        if(len(j['ProfileList']) == 0):
            print(res.text)
            return 'error'
        else:
            mail=j['ProfileList'][0]['Value']
            str = "{0}\t{1}\n".format(uid,mail)
            return str
    except KeyboardInterrupt:
        return 'break'
    except:
        print(uid)
        return 'error'

stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

result_file = open("D:\\QIAN\\CODE\\oschina\\userprofile\\email_"+ stamp + ".txt", "w")
error_file = open("D:\\QIAN\\CODE\\oschina\\userprofile\\error_"+ stamp + ".txt", "w")

text_file = open("D:\\QIAN\\CODE\\oschina\\userprofile\\uid_20170628.txt", "r")

lines = [line.rstrip('\n') for line in text_file]
i=0
try:
    for uid in lines:
        i = i+ 1
        mail=getmail(uid)
        print("{0}\t{1}\t{2}".format(i,uid,mail))
        
        if(mail == 'error'):
            error_file.write("{0}\n".format(uid))
        elif(mail=='break'):
            break;
        else:
            print("{0}\t{1}\t{2}".format(i,uid,mail))
            result_file.write(mail)
    print('done')
finally:
    result_file.flush()
    result_file.close()
    text_file.close()
    error_file.flush()
    error_file.close()

    